package com.gz.mylife.app;

import java.lang.ref.WeakReference;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.MenuItemCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.android.app.sdk.AliPay;
import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.im.ChatSession;
import com.gz.mylife.util.ObserverWorker;
import com.gz.mylife.util.ObserverWorker.ObserverMessage;
import com.gz.mylife.util.ToastUtils;
import com.gz.mylife.widget.LoadingCover;
import com.gz.mylife.widget.OfflineDialog;
import com.gz.mylife.widget.LoadingCover.OnLoadingCoverRefreshListener;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.zl.smartmall.library.IPay;
import com.zl.smartmall.library.IShoppingCart;
import com.zl.smartmall.library.ISmartMall;
import com.zl.smartmall.library.concurrent.ThreadExecutor;
import com.zl.smartmall.library.listener.AddToShoppingCartMultiListener;
import com.zl.smartmall.library.listener.AlipayPayListener;
import com.zl.smartmall.library.listener.CancelOrderListener;
import com.zl.smartmall.library.listener.ConfirmTheGoodsListener;
import com.zl.smartmall.library.listener.OrderDetailListener;
import com.zl.smartmall.library.listener.WechatPayListener;
import com.zl.smartmall.library.po.OrderCommoditiesInfo;
import com.zl.smartmall.library.po.OrderDetailInfo;
import com.zl.smartmall.library.po.WechatPayInfo;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.PreferenceModel;
import com.zl.smartmall.library.util.Tools;

public class OrderDetail extends BaseActivity implements OnClickListener, OnLoadingCoverRefreshListener, Observer {

	private static final String TAG = OrderDetail.class.getSimpleName();
	
	private static final String ALIPAY_PAY_SUCCESS = "9000";
	private static final String ALIPAY_PAY_SYSTEM_EXCEPTION = "4000";
	private static final String ALIPAY_PAY_ORDER_FAILED = "4001";
	private static final String ALIPAY_PAY_CANCLE = "6001";
	private static final String ALIPAY_PAY_NETWORK_ERROR = "6002";
	private static final String ALIPAY_PAY_PROCESSING = "8000";
	
	private static final int MSG_ALIPAY_RESULT = 1;
	
	
	private String mSn;
	
	private AddToShoppingCartMultiListener mAddToShoppingCartMultiListener;
	private CancelOrderListener mCancelOrderListener;
	private IWXAPI mWechatApi;
	private LayoutInflater mInflater;
	private MyHandler mHandler;
//	private OrderCancelHttpHandler mOrderCancelHttpHandler;
	private OrderDetailListener mOrderDetailListener;
	private OrderDetailInfo mOrderDetailInfo;	
	private Map<String, String> mResultStatus;
	private ConfirmTheGoodsListener mConfirmTheGoodsListener;
	
	private Button mWechatPay;
	private Button mAlipayPay;
	private Button btn_card_pay;
	private View mPayLayout;
	private LinearLayout mProductItemLayout;
	private LoadingCover mLoadingCover;
	private OfflineDialog mOfflineDialog;
	private TextView mOrderCode;
	private TextView mOrderStatus;
	private TextView mProductNum;
	private TextView mBottomPriceSum;
	private TextView mTopPriceSum;
	private TextView mReceiverName;
	private TextView mReceiverPhone;
	private TextView mReceiverAddress;
//	private TextView mInvoiceHead;
//	private TextView mInvoiceDetail;
	private TextView mProductPriceSum;
	private TextView mDeliveryCost;
//	private TextView mLogisticsInfo;
	private TextView mRemarks;
	private TextView mTvExpress;
	private TextView mDeliveryWay;
	private TextView mInvoice;
//	private TextView mLogisticsNo;
//	private View mLine;
//	private TextView mContactCustomerService;
	private Button mApplyExchange;
	private TextView mGoldDeduction;
//	private View mHeadLayout;
	private View mLayoutExpress;
	private Button mConfirmTheGoods;
	private Dialog mConfirmDialog;
	private TextView myself_address;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order_detail);

//		mWechatApi = WXAPIFactory.createWXAPI(this, Define.APP_ID_WECHAT);
		mWechatApi = WXAPIFactory.createWXAPI(this, Define.APP_ID_WECHAT);
		mWechatApi.registerApp(Define.APP_ID_WECHAT);
		mSn = getIntent().getStringExtra("sn");
		mInflater = getLayoutInflater();
		mHandler = new MyHandler(this);
		mResultStatus = new HashMap<String, String>();
		mResultStatus.put(ALIPAY_PAY_SUCCESS, "支付成功");
		mResultStatus.put(ALIPAY_PAY_SYSTEM_EXCEPTION, "系统异常");
		mResultStatus.put(ALIPAY_PAY_ORDER_FAILED, "支付失败");
		mResultStatus.put(ALIPAY_PAY_CANCLE, "您已取消支付");
		mResultStatus.put(ALIPAY_PAY_NETWORK_ERROR, "网络连接异常");
		mResultStatus.put(ALIPAY_PAY_PROCESSING, "支付处理中");
		initListener();
		ObserverWorker.getInstance().registerObserver(Define.OBSERVER_TYPE_REFRESH_ORDER_DETAIL, this);
		
		
//		mActionBar.setTitle("订单详情");
		setActionbarTitle("订单详情", true);
		mPayLayout = findViewById(R.id.layout_pay_button);
		mWechatPay = (Button) findViewById(R.id.btn_wechat_pay);
		mWechatPay.setOnClickListener(this);
		mAlipayPay = (Button) findViewById(R.id.btn_alipay_pay);
		mAlipayPay.setOnClickListener(this);
		/*btn_card_pay = (Button) findViewById(R.id.btn_card_pay);
		btn_card_pay.setOnClickListener(this);*/
		mOrderCode = (TextView) findViewById(R.id.tv_order_code);
		mOrderStatus = (TextView) findViewById(R.id.tv_order_status);
		mProductNum = (TextView) findViewById(R.id.tv_product_num);
		mBottomPriceSum = (TextView) findViewById(R.id.tv_sum_price);
		mTopPriceSum = (TextView) findViewById(R.id.tv_top_price_sum);
		mReceiverName = (TextView) findViewById(R.id.tv_receiver_name);
		myself_address = (TextView)findViewById(R.id.myself_address);
		mReceiverPhone = (TextView) findViewById(R.id.tv_receiver_phone);
		mReceiverAddress = (TextView) findViewById(R.id.tv_receiver_address);
//		mInvoiceHead = (TextView) findViewById(R.id.tv_invoice_head);
//		mInvoiceDetail = (TextView) findViewById(R.id.tv_invoice_detail);
		mProductPriceSum = (TextView) findViewById(R.id.tv_product_price_sum);
		mDeliveryCost = (TextView) findViewById(R.id.tv_delivery_cost);
//		mLine = findViewById(R.id.line_1);
//		mLogisticsInfo = (TextView) findViewById(R.id.tv_logistics_info);
//		mLogisticsNo = (TextView) findViewById(R.id.tv_logistics_no);
		mRemarks = (TextView) findViewById(R.id.tv_remarks);
//		mContactCustomerService = (TextView) findViewById(R.id.btn_customer_service);
//		mContactCustomerService.setOnClickListener(this);
		mApplyExchange = (Button) findViewById(R.id.btn_apply_exchange);
		mApplyExchange.setOnClickListener(this);
		mConfirmTheGoods = (Button) findViewById(R.id.btn_confirm_the_goods);
		mConfirmTheGoods.setOnClickListener(this);
//		mHeadLayout = findViewById(R.id.layout_order_head);
		mGoldDeduction = (TextView) findViewById(R.id.tv_gold_deduction);
		mTvExpress = (TextView) findViewById(R.id.tv_express);
		mLayoutExpress = findViewById(R.id.layout_express);
		mDeliveryWay = (TextView) findViewById(R.id.tv_delivery_way);
		mInvoice = (TextView) findViewById(R.id.tv_invoice);
		
		mLoadingCover = (LoadingCover) findViewById(R.id.layout_loading_cover);
		mLoadingCover.setOnLoadingCoverRefreshListener(this);
		mOfflineDialog = (OfflineDialog) mInflater.inflate(R.layout.offline_dialog, null);
		mProductItemLayout = (LinearLayout) findViewById(R.id.layout_product_item);
		View confirmView = mInflater.inflate(R.layout.confirm_the_goods_dialog, null);
		confirmView.findViewById(R.id.btn_confirm).setOnClickListener(this);
		confirmView.findViewById(R.id.btn_cancel).setOnClickListener(this);
		mConfirmDialog = new Dialog(this, R.style.DialogTheme);
		mConfirmDialog.setContentView(confirmView);
		mConfirmDialog.setCancelable(true);
//		initHandler();
//		loadDataFromServer();
		ISmartMall.getInstance().getOrderDetail(mSn, mOrderDetailListener);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mHandler.release();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.order_detail, menu);
		MenuItemCompat.setShowAsAction(menu.findItem(R.id.action_customer_service), 
				MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		return true;
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
//		if(mOrderDetailInfo != null && mOrderDetailInfo.getOrderStatus() == Define.ORDER_STATUS_NO_PAY) {
//			MenuItemCompat.setShowAsAction(menu.findItem(R.id.action_cancel_order), 
//					MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
//		}else {
//			MenuItemCompat.setShowAsAction(menu.findItem(R.id.action_cancel_order), MenuItemCompat.SHOW_AS_ACTION_NEVER);
//			menu.findItem(R.id.action_cancel_order).setVisible(false);
//		}
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
//		case android.R.id.home:
//			if(getIntent().getBooleanExtra("startMyOrder", false)){
//				Intent intent = new Intent(getApplicationContext(), Plaza.class);
//				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//				intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//				intent.putExtra("tab_index", 3);
//				startActivity(intent);
//			}
//			finish();
//			return true;

//		case R.id.action_cancel_order:
//			orderCancelAction();
//			return true;
			
		case R.id.action_customer_service:
			if(mOrderDetailInfo.getCustomerServiceInfos().size() > 0) {
				Intent intent = new Intent();
	//			intent.setClass(getApplicationContext(), PrivateLetter.class);
				intent.setClass(getApplicationContext(), ChatSession.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				intent.putExtra("fuid", mOrderDetailInfo.getCustomerServiceInfos().get(0).getUid());
				intent.putExtra("nickname", mOrderDetailInfo.getCustomerServiceInfos().get(0).getNickname());
				intent.putExtra("gender", mOrderDetailInfo.getCustomerServiceInfos().get(0).getGender());
				intent.putExtra("face", mOrderDetailInfo.getCustomerServiceInfos().get(0).getFace());
				startActivity(intent);
			}
			return true;
			
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode) {
		case Define.ACTIVITY_CODE_APPLY_EXCHANGE:
			//重新刷新订单状态
			setResult(Define.ACTIVITY_CODE_APPLY_EXCHANGE);
			ISmartMall.getInstance().getOrderDetail(mSn, mOrderDetailListener);
			break;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent;
		switch (v.getId()) {
		case R.id.btn_wechat_pay:
			wechatPay();
			break;

		case R.id.btn_alipay_pay:
			alipay();
			break;
			
		case R.id.btn_comment:
			intent = new Intent(getApplicationContext(), ProductCommentIssue.class);
			intent.putExtra("productId", (Integer) v.getTag());
			startActivity(intent);
			break;
		/*case R.id.btn_card_pay:
			intent = new Intent(getApplicationContext(), Browser.class);
			intent.putExtra("url", Constants.URL_pay_online+"?order_no="+mSn);
			intent.putExtra("title", "兴业快捷支付");
			startActivity(intent);
			break;*/
//		case R.id.btn_customer_service:
//			if(v.getTag() != null) {
//				intent = new Intent();
//				intent.setClass(getApplicationContext(), ChatSession.class);
//				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//				intent.putExtra("fuid", ((CustomerServiceModel) v.getTag()).getUid());
//				intent.putExtra("nickname", ((CustomerServiceModel) v.getTag()).getNickname());
//				intent.putExtra("gender", ((CustomerServiceModel) v.getTag()).getGender());
//				intent.putExtra("face", ((CustomerServiceModel) v.getTag()).getFace());
//				startActivity(intent);
//			}
//			break;
			
		case R.id.btn_apply_exchange:
			if((Boolean) v.getTag()) {
				try {
					intent = new Intent(getApplicationContext(), ApplyExchange.class);
					intent.putExtra("order", buildApplyExchangeInfo());
					startActivityForResult(intent, Define.ACTIVITY_CODE_APPLY_EXCHANGE);
					
				} catch (JSONException e) {
					CrashHandler.e(e);
				}
			}else {
				orderCancelAction();
			}
			break;
			
		case R.id.btn_confirm_the_goods:
			mConfirmDialog.show();
			break;
			
		case R.id.btn_confirm:
			ISmartMall.getInstance().confirmTheGoods(mSn, mConfirmTheGoodsListener);
			
		case R.id.btn_cancel:
			mConfirmDialog.dismiss();
			break;
		}
		
	}

	@Override
	public void onLoadingCoverRefresh() {
		// TODO Auto-generated method stub
		ISmartMall.getInstance().getOrderDetail(mSn, mOrderDetailListener);
	}
	
	private String buildApplyExchangeInfo() throws JSONException {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("receiver", mOrderDetailInfo.getDeliveryAddress().getReceiver());
		jsonObject.put("orderCode", mOrderDetailInfo.getOrderCode());
		jsonObject.put("money", mOrderDetailInfo.getMoney());
		jsonObject.put("orderStatus", mOrderDetailInfo.getOrderStatus());
		JSONArray jsonArray = new JSONArray();
		for(int i = 0; i < mOrderDetailInfo.getProductInfos().size(); i++) {
			JSONObject productObject = new JSONObject();
			productObject.put("product_id", mOrderDetailInfo.getProductInfos().get(i).getProductId());
			productObject.put("sale_price", mOrderDetailInfo.getProductInfos().get(i).getPrice());
			productObject.put("product_num", mOrderDetailInfo.getProductInfos().get(i).getBuyNum());
			productObject.put("product_title", mOrderDetailInfo.getProductInfos().get(i).getProductTitle());
			productObject.put("title_pic", mOrderDetailInfo.getProductInfos().get(i).getProductPicture());
			productObject.put("product_name", mOrderDetailInfo.getProductInfos().get(i).getProductName());
			productObject.put("shop_id", mOrderDetailInfo.getProductInfos().get(i).getShopId());
			productObject.put("act_id", mOrderDetailInfo.getProductInfos().get(i).getActivitiesId());
			jsonArray.put(productObject);
		}
		jsonObject.put("product", jsonArray);
		
		return jsonObject.toString();
	}
	
	private String getShoppingCartJson() {
		try {
			JSONArray jsonArray = new JSONArray();
			List<OrderCommoditiesInfo> productInfos = mOrderDetailInfo.getProductInfos();
			for(OrderCommoditiesInfo info : productInfos) {
				JSONObject jsonObject = new JSONObject();
	//			{"act_id":1,"shop_id":3,"product_id":5,"num":45}
					jsonObject.put("act_id", info.getActivitiesId());
					jsonObject.put("shop_id", info.getShopId());
					jsonObject.put("product_id", info.getProductId());
					jsonObject.put("num", info.getBuyNum());
					jsonArray.put(jsonObject);
			}
			return Tools.Base64Encode(jsonArray.toString());
			
		} catch (JSONException e) {
			CrashHandler.e(e);
		}
		
		return "[]";
	}
	
	private void alipay() {
		IPay.getInstance().alipayPay(mSn, new AlipayPayListener() {
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), "支付失败, 请重新操作");
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), Define.MSG_NO_NETWORK);
			}
			
			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onResponseSuccess(final String sign) {
				// TODO Auto-generated method stub
				ThreadExecutor.getInstance().execute(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub
						AliPay alipay = new AliPay(OrderDetail.this, mHandler);
						
						//设置为沙箱模式，不设置默认为线上环境
						//alipay.setSandBox(true);

						String result = alipay.pay(sign);

						CrashHandler.d(TAG, "result = " + result);
						Message msg = new Message();
						msg.what = MSG_ALIPAY_RESULT;
						msg.obj = result;
						mHandler.sendMessage(msg);
					}
					
				});
			}
		});
	}
	
	private void wechatPay() {
		IPay.getInstance().wechatPay(mSn, new WechatPayListener() {
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), "支付失败, 请重新操作");
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), Define.MSG_NO_NETWORK);
			}
			
			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onResponseSuccess(WechatPayInfo wechatPayInfo) {
				// TODO Auto-generated method stub
				PayReq req = new PayReq();
				req.appId = Define.APP_ID_WECHAT;
				req.partnerId = wechatPayInfo.getPartnerId();
				req.prepayId = wechatPayInfo.getPrePayId();
				req.nonceStr = wechatPayInfo.getNonceStr();
				req.timeStamp = String.valueOf(wechatPayInfo.getTimeStamp());
				req.packageValue = "Sign=" + wechatPayInfo.getPackageValue();
//				req.packageValue = "Sign=WXPay";


//				List<NameValuePair> signParams = new LinkedList<NameValuePair>();
//				signParams.add(new BasicNameValuePair("appid", req.appId));
//				signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
//				signParams.add(new BasicNameValuePair("package", req.packageValue));
//				signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
//				signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
//				signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
//
//				req.sign = genAppSign(signParams);
				
				req.sign = wechatPayInfo.getSign();
				
				// 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
				mWechatApi.registerApp(Define.APP_ID_WECHAT);
				mWechatApi.sendReq(req);
			}
		});
	}
	

	private String genAppSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Define.APP_ID_WECHAT);

		String appSign = getMessageDigest(sb.toString().getBytes()).toUpperCase();
		Log.e("orion",appSign);
		return appSign;
	}

	public final static String getMessageDigest(byte[] buffer) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(buffer);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}
	
	private void initListener() {
		mAddToShoppingCartMultiListener = new AddToShoppingCartMultiListener() {
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				//重新刷新订单状态
				ISmartMall.getInstance().getOrderDetail(mSn, mOrderDetailListener);
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), Define.MSG_NO_NETWORK);
			}
			
			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onResponseSuccess() {
				// TODO Auto-generated method stub
				int cartNum = PreferenceModel.getInt(Define.PREFERENCE_KEY_SHOPPING_CART_NUM, 0);
				PreferenceModel.putInt(Define.PREFERENCE_KEY_SHOPPING_CART_NUM, 
						cartNum + mOrderDetailInfo.getProductInfos().size());
				setResult(Define.ACTIVITY_CODE_ORDER_CANCEL);
				//重新刷新订单状态
				ISmartMall.getInstance().getOrderDetail(mSn, mOrderDetailListener);
				
				//通过广播刷新购物车
				Intent broastIntent = new Intent(Define.ACTION_REFRESH_SHOPPING_CART);
				sendBroadcast(broastIntent);
			}
		};
		
		mCancelOrderListener = new CancelOrderListener() {
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), "取消订单失败, 请重试");
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), Define.MSG_NO_NETWORK);
			}
			
			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), "操作订单不存在");
			}
			
			@Override
			public void onResponseSuccess() {
				// TODO Auto-generated method stub
				//返回商品到购物车
				IShoppingCart.getInstance().addToShoppingCartMulti(getShoppingCartJson(), mAddToShoppingCartMultiListener);
			}
		};
		
		mConfirmTheGoodsListener = new ConfirmTheGoodsListener() {
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), Define.MSG_OPERATE_FAILED_RETRY);
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				ToastUtils.showToast(getApplicationContext(), Define.MSG_NO_NETWORK);
			}
			
			@Override
			public void onResponseSuccess() {
				// TODO Auto-generated method stub
				setResult(Define.ACTIVITY_CODE_ORDER_SIGN);
				ISmartMall.getInstance().getOrderDetail(mSn, mOrderDetailListener);
			}
		};
		
		mOrderDetailListener = new OrderDetailListener() {
			
			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed();
			}
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineDialog.show();
				mLoadingCover.onRefreshFailed(Define.MSG_OFFLINE_ERROR);
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed(Define.MSG_NO_NETWORK);
			}
			
			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub
				mLoadingCover.onRefreshFailed(Define.MSG_NO_MORE_DATA);
			}
			
			@Override
			public void onResponseSuccess(OrderDetailInfo model) {
				// TODO Auto-generated method stub
				mOrderDetailInfo = model;
				initProductItemLayout(model);
				mOrderCode.setText("订单号：" + model.getOrderCode());
				mProductNum.setText("您购买了 " + model.getProductInfos().size() + " 件产品");
				mBottomPriceSum.setText("￥" + new DecimalFormat("0.00").format(model.getMoney()));
				mTopPriceSum.setText("金额：￥" + new DecimalFormat("0.00").format(model.getMoney()));
				mGoldDeduction.setText("金豆抵扣：￥" + new DecimalFormat("0.00").format(model.getGoldToMoney()));
				//是否退换货，不是的话就显示支付状态，否则显示退换货处理状态
				if(model.getIsReturn() == 0 || model.getOrderStatus() == Define.ORDER_STATUS_CANCEL
						 || model.getOrderStatus() == Define.ORDER_STATUS_INVALIDATE
						 || model.getOrderStatus() == Define.ORDER_STATUS_SIGN_IN) {
					mOrderStatus.setText(obtainStatus(model.getOrderStatus()));
					
				}else if(model.getIsReturn() == 1){
					//退货处理
					switch (model.getReturnStatus()) {
					case Define.ORDER_EXCHANGE_STATUS_UNDER_CHECK:
//						mOrderStatus.setText("审核中");
						mOrderStatus.setText(Define.ORDER_EXCHANGE_STATUS_UNDER_CHECK_TEXT);
						break;

					case Define.ORDER_EXCHANGE_STATUS_UNDER_PROCESS:
//						mOrderStatus.setText("处理中");
						mOrderStatus.setText(Define.ORDER_EXCHANGE_STATUS_UNDER_CHECK_TEXT);
						break;
						
					case Define.ORDER_EXCHANGE_STATUS_REJECT:
						mOrderStatus.setText("被驳回");
						break;
						
					case Define.ORDER_EXCHANGE_STATUS_FINISH:
//						mOrderStatus.setText("退货成功");
						mOrderStatus.setText(Define.ORDER_EXCHANGE_STATUS_FINISH_TEXT);
						break;
					}
				}else if(model.getIsReturn() == 2) {
					//换货处理
					switch (model.getReturnStatus()) {
					case Define.ORDER_EXCHANGE_STATUS_UNDER_CHECK:
//						mOrderStatus.setText("审核中");
						mOrderStatus.setText(Define.ORDER_EXCHANGE_STATUS_UNDER_CHECK_TEXT);
						break;

					case Define.ORDER_EXCHANGE_STATUS_UNDER_PROCESS:
//						mOrderStatus.setText("处理中");
						mOrderStatus.setText(Define.ORDER_EXCHANGE_STATUS_UNDER_CHECK_TEXT);
						break;
						
					case Define.ORDER_EXCHANGE_STATUS_REJECT:
						mOrderStatus.setText("被驳回");
						break;
						
					case Define.ORDER_EXCHANGE_STATUS_FINISH:
//						mOrderStatus.setText("换货成功");
						mOrderStatus.setText(Define.ORDER_EXCHANGE_STATUS_FINISH_TEXT);
						break;
					}
				}
				
				//处理状态圆背景和字体颜色
				if(model.getOrderStatus() == Define.ORDER_STATUS_DELIVERIED ||
						model.getOrderStatus() == Define.ORDER_STATUS_PAID ||
						model.getOrderStatus() == Define.ORDER_STATUS_STOCK_UP) {
					mOrderStatus.setBackgroundResource(R.drawable.bg_order_status_green_circle);
				}else {
					mOrderStatus.setBackgroundResource(R.drawable.bg_order_status_dark_circle);
				}
				
				if(model.getDeliveryAddress() != null) {
					mReceiverName.setText("收货人: " + model.getDeliveryAddress().getReceiver());
					mReceiverPhone.setText(model.getDeliveryAddress().getPhone());
					mReceiverAddress.setText(model.getDeliveryAddress().getFullAddress());
				}
				if (!" ".equals(model.getStoreHouse())&&!model.getStoreHouse().isEmpty()) {
					myself_address.setText("自提地址："+model.getStoreHouse());
				}else {
					myself_address.setVisibility(View.GONE);
				}
				
				if(model.getInvoiceInfo() != null) {
					mInvoice.setText(model.getInvoiceInfo().getInvoiceHead());
				}else {
					mInvoice.setText("不需要发票");
				}
				
				mProductPriceSum.setText("金额总计：￥" + new DecimalFormat("0.00").format((model.getMoney() - model.getExpressInfo().getDeliveryCost())));
				mDeliveryCost.setText("配送费用 ：￥" + new DecimalFormat("0.00").format(model.getExpressInfo().getDeliveryCost()));
				
				if(model.getOrderStatus() == Define.ORDER_STATUS_NO_PAY) {
					mPayLayout.setVisibility(View.VISIBLE);
					mTopPriceSum.setTextColor(getResources().getColor(R.color.white));

				}else {
					mPayLayout.setVisibility(View.GONE);
					mTopPriceSum.setTextColor(getResources().getColor(R.color.RGB_888888));
				}
				
				//申请退换货按钮
				if(model.getOrderStatus() == Define.ORDER_STATUS_NO_PAY) {
					//未支付
					mApplyExchange.setTag(false);
					mApplyExchange.setText(getResources().getString(R.string.cancel_order));
					mApplyExchange.setVisibility(View.VISIBLE);		
					
				}else if(model.getReturnStatus() == Define.ORDER_EXCHANGE_STATUS_REJECT) {
					//退换货被驳回
					mApplyExchange.setVisibility(View.VISIBLE);
					mApplyExchange.setTag(true);
					mApplyExchange.setText(getResources().getString(R.string.apply_exchange));
					
				}else if(model.getReturnStatus() == Define.ORDER_EXCHANGE_STATUS_FINISH || 
						model.getReturnStatus() == Define.ORDER_EXCHANGE_STATUS_UNDER_CHECK ||
						model.getReturnStatus() == Define.ORDER_EXCHANGE_STATUS_UNDER_PROCESS){
					mApplyExchange.setVisibility(View.GONE);
					
				}else if(model.getOrderStatus() == Define.ORDER_STATUS_PAID || 
							model.getOrderStatus() == Define.ORDER_STATUS_DELIVERIED || 
							model.getOrderStatus() == Define.ORDER_STATUS_STOCK_UP){
//					model.getOrderStatus() == Define.ORDER_STATUS_SIGN_IN
					mApplyExchange.setVisibility(View.VISIBLE);
					mApplyExchange.setTag(true);
					mApplyExchange.setText(getResources().getString(R.string.apply_exchange));
					
				}else {
					mApplyExchange.setVisibility(View.GONE);
				}
				
				//确认收货按钮
				/*if(model.getReturnStatus() != Define.ORDER_EXCHANGE_STATUS_FINISH &&
						model.getOrderStatus() != Define.ORDER_STATUS_CANCEL &&
						model.getOrderStatus() != Define.ORDER_STATUS_NO_PAY && 
						model.getOrderStatus() != Define.ORDER_STATUS_SIGN_IN) {
					mConfirmTheGoods.setVisibility(View.VISIBLE);
					
				}else {
					
				}*/
				mConfirmTheGoods.setVisibility(View.GONE);
				if(model.getExpressInfo() != null) {
					mDeliveryWay.setText(model.getExpressInfo().getExpressHabit());
				}
				if(model.getExpressInfo() != null &&
						!TextUtils.isEmpty(model.getExpressInfo().getExpressCompany()) &&
						!TextUtils.isEmpty(model.getExpressInfo().getExpressSn())) {
					String expressCompany = model.getExpressInfo().getExpressCompany();
					String expressSn = model.getExpressInfo().getExpressSn(); 
					mTvExpress.setText(TextUtils.isEmpty(expressCompany + expressSn) ? "暂无物流信息" : expressCompany + expressSn);
					mLayoutExpress.setVisibility(View.VISIBLE);
					
				}else {
//					mTvExpress.setText("暂无物流信息");
					mLayoutExpress.setVisibility(View.GONE);
				}
//				if(model.getExpressModel() != null && !TextUtils.isEmpty(model.getExpressModel().getExpressCompany())) {
//					mLogisticsInfo.setText("物流信息：" + model.getExpressModel().getExpressCompany());
//				}else {
//					mLogisticsInfo.setVisibility(View.GONE);
//				}
//				
//				if(model.getExpressModel() != null && !TextUtils.isEmpty(model.getExpressModel().getExpressSn())){
//					mLogisticsNo.setText("快递单号：" + model.getExpressModel().getExpressSn());
//				}else {
//					mLogisticsNo.setVisibility(View.GONE);
//				}
				
				if(!TextUtils.isEmpty(model.getRemarks())) {
					mRemarks.setText(model.getRemarks());
				}else {
					mRemarks.setText("无");
				}
				
//				if(model.getCustomerServiceInfos().size() > 0) {
//					mContactCustomerService.setTag(model.getCustomerServiceInfos().get(0));
//				}
				
				mLoadingCover.onRefreshSuccess();
				invalidateOptionsMenu();
			}
		};
	}
	
	private void initProductItemLayout(OrderDetailInfo model) {
		mProductItemLayout.removeAllViews();
		for(int i = 0; model.getProductInfos() != null && i < model.getProductInfos().size(); i++) {
			View root = mInflater.inflate(R.layout.order_detail_product_item, null);
			ImageView icon = (ImageView) root.findViewById(R.id.iv_product_icon);
			TextView price = (TextView) root.findViewById(R.id.tv_price);
			TextView num = (TextView) root.findViewById(R.id.tv_num);
			TextView intro = (TextView) root.findViewById(R.id.tv_product_intro);
			Button comment = (Button) root.findViewById(R.id.btn_comment);
			comment.setOnClickListener(this);
			comment.setTag(model.getProductInfos().get(i).getProductId());
			if(model.getOrderStatus() == Define.ORDER_STATUS_SIGN_IN /*|| model.getOrderStatus() == Define.ORDER_STATUS_PAID*/) {
				comment.setVisibility(View.VISIBLE);
			}else {
				comment.setVisibility(View.GONE);
			}
			
			price.setText("￥" + new DecimalFormat("0.00").format(model.getProductInfos().get(i).getPrice()));
			num.setText("x" + model.getProductInfos().get(i).getBuyNum());
			intro.setText(model.getProductInfos().get(i).getProductTitle());
			ImageLoader.getInstance().displayImage(model.getProductInfos().get(i).getProductPicture(), icon);
			mProductItemLayout.addView(root);
			
			if(i < model.getProductInfos().size() - 1) {
				View view = new View(this);
				mProductItemLayout.addView(view);
				view.setBackgroundColor(getResources().getColor(R.drawable.divider_deep));
				LinearLayout.LayoutParams params = (LayoutParams) view.getLayoutParams();
				params.width = android.view.ViewGroup.LayoutParams.MATCH_PARENT;
				params.height = Tools.dip2px(getApplicationContext(), 0.5f);
				params.leftMargin = Tools.dip2px(getApplicationContext(), 15);
			}
		}
	}
	
	private String obtainStatus(int status) {
		String name = "";
		switch (status) {
		case Define.ORDER_STATUS_NO_PAY:
			name = Define.ORDER_STATUS_NO_PAY_TEXT;
			break;

		case Define.ORDER_STATUS_PAID:
			name = Define.ORDER_STATUS_PAID_TEXT;
			break;
			
		case Define.ORDER_STATUS_DELIVERIED:
			name = mOrderDetailInfo.getDeliveryWay() == Constants.PAY_ON_DELIVERY ? Define.ORDER_STATUS_DELIVERIED_TEXT : 
				Define.ORDER_STATUS_TAKE_SELF_TEXT;
			break;
			
		case Define.ORDER_STATUS_SIGN_IN:
			name = Define.ORDER_STATUS_SIGN_IN_TEXT;
			break;
			
		case Define.ORDER_STATUS_INVALIDATE:
			name = Define.ORDER_STATUS_INVALIDATE_TEXT;
			break;
			
		case Define.ORDER_STATUS_CANCEL:
			name = Define.ORDER_STATUS_CANCEL_TEXT;
			break;
			
		case Define.ORDER_STATUS_STOCK_UP:
			name = Define.ORDER_STATUS_STOCK_UP_TEXT;
			break;
		};
		
		return name;
	}

	private void orderCancelAction() {
		// TODO Auto-generated method stub
		ISmartMall.getInstance().cancelOrder(mSn, mCancelOrderListener);
	}
	
	private String getAlipayCode(String src, String startTag, String endTag) {
		String content = src;
		int start = src.indexOf(startTag);
		start += startTag.length();

		try {
			if (endTag != null) {
				int end = src.indexOf(endTag);
				content = src.substring(start, end);
			} else {
				content = src.substring(start);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return content;
	}

	private AlipayResult parseResult(String result) {
		
		try {
			AlipayResult alipayResult = new AlipayResult();
			String src = result.replace("{", "");
			src = src.replace("}", "");
			String rs = getAlipayCode(src, "resultStatus=", ";memo");
			if (mResultStatus.containsKey(rs)) {
				alipayResult.key = rs;
				alipayResult.result = mResultStatus.get(rs);
				return alipayResult;
			} else {
				alipayResult.key = rs;
				alipayResult.result = "其他错误";
				return alipayResult;
			}

			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	static class AlipayResult {
		public String key;
		public String result;
	}
	
	private static class MyHandler extends Handler {

		private OrderDetail mOuter;

		public MyHandler(OrderDetail outer) {
			mOuter = outer;
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case MSG_ALIPAY_RESULT:
				AlipayResult alipayResult = mOuter.parseResult((String) msg.obj);
				ToastUtils.showToast(mOuter, alipayResult.result);
				if(ALIPAY_PAY_SUCCESS.equals(alipayResult.key)) {
					mOuter.setResult(Define.ACTIVITY_CODE_ORDER_PAID);
					mOuter.finish();
				}
				break;
			}
		}

		public void release() {
			new WeakReference<OrderDetail>(mOuter);
		}
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ObserverMessage observerMessage = (ObserverMessage) data;
		if(observerMessage.type == Define.OBSERVER_TYPE_REFRESH_ORDER_DETAIL) {
//			onLoadingCoverRefresh();
			setResult(Define.ACTIVITY_CODE_ORDER_PAID);
			finish();
		}
	}

}
